package jrmob.yonyou.com.commonlib.login.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONObject;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import jrmob.yonyou.com.commonlib.R;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.NetUtilContant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.NetUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;
import jrmob.yonyou.com.commonlib.login.bean.UserInfo_lib;
import jrmob.yonyou.com.commonlib.receiver.OpenAppReceiver_lib;
import jrmob.yonyou.com.commonlib.view.SlideSwitch;


/**
 * 登录界面
 * Created by zhangguang on 16/10/22.
 */

public class LoginBaseActivity_lib extends BaseActivityMob_lib {


    private TextView loginbase;
    private EditText username;
    private EditText password;


    private String type = Constant.apptype; // 用来记录从哪个module来的登录
    private String packagename;
    private String openactivity;

    private SlideSwitch switchs;
    private ImageView iv_net_setting;


    // 登录回调（需要传进来监听）
    public LoginListener loginlistener = null;


    public LoginBaseActivity_lib(LoginListener loginlistener) {
        this.loginlistener = loginlistener;
    }

    public LoginBaseActivity_lib() {
        this.loginlistener = null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_loginbase_lib);

        initView();
        setDefault();
        initListener();
        initData();


    }


    @Override
    protected void onStart() {
        super.onStart();



        if (isSurpass6Version()){
            List<String> perimess = new ArrayList<String>();
            perimess.add("android.permission.ACCESS_WIFI_STATE");
            perimess.add("android.permission.INTERNET");
            perimess.add("android.permission.WRITE_EXTERNAL_STORAGE");
            perimess.add("android.permission.READ_PHONE_STATE");
            perimess.add("android.permission.ACCESS_FINE_LOCATION");
            // 获取没有权限的列表s
            List<String> ls = getDeniedPermissions(perimess.toArray(new String [0]));

            requestPermission(ls.toArray(new String[0]), 3);
        }



    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
    }


    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        mActivity.showToast("你拒绝了权限,可能导致部分功能不可用.");
    }

    @Override
    public void initView() {

        loginbase = (TextView) findViewById(R.id.loginbase_app);
        loginbase.setBackgroundColor(getResources().getColor(R.color.ff3399));


        username = (EditText) findViewById(R.id.username_app);
        password = (EditText) findViewById(R.id.password_app);
        switchs = (SlideSwitch) findViewById(R.id.switchs);
        iv_net_setting = (ImageView) findViewById(R.id.iv_net_setting);







    }


    private void setDefault() {

//        username.setText("zhangguang");
//        password.setText("1111111q");

        String ip  = readLocationValue("ip");
        String port  = readLocationValue("port");
        // 有为空的时候，使用默认的
        if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)){
            BaseApp_lib.setIp(NetUtilContant.ip);
            BaseApp_lib.setPort(NetUtilContant.port);
        }else{
            BaseApp_lib.setIp(ip);
            BaseApp_lib.setPort(port);
        }


        // 自动登录按钮
        String autoflag = readLocationValue("autologin");
        if (autoflag.equals("true")){
            switchs.setState(true);
        }



    }

    @Override
    public void initListener() {


        iv_net_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeNetSetting();
            }
        });

        // 开关监听
        switchs.setSlideListener(new SlideSwitch.SlideListener() {

            @Override
            public void open() {
                writeLocationFile("autologin","true");
            }

            @Override
            public void close() {
                writeLocationFile("autologin","false");
            }
        });




        Intent intent = getIntent();
        if (null != intent) {
            Bundle extras = intent.getExtras();
            LogUtils.e(extras);
            if (null != extras) {
                type = extras.getString(Constant.type, type);// 默认是从移动审批来的
                packagename = extras.getString(Constant.packagename, "");
                openactivity = extras.getString(Constant.openactivity, "");

            }

        }



        loginbase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                userName = username.getText().toString();
                userPW = password.getText().toString();


                if (TextUtils.isEmpty(userName)) {
                    showToast("用户名不可为空");
                    return;
                }

                if (TextUtils.isEmpty(userPW)) {
                    showToast("密码不可为空");
                    return;
                }

                // 判断网络
                if (!NetUtil.isNetConnected(LoginBaseActivity_lib.this)) {
                    showToast("当前网络不可用,请检查!");
                    return;
                }

                callServiceEx(false);

            }
        });
    }


    private void changeNetSetting() {
        String maIP = readLocationValue("ip");
        String maPort = readLocationValue("port");

        View view = View.inflate(this, R.layout.net_setting_lib, null);
        final EditText editText = (EditText) view.findViewById(R.id.et_ipport);
        if (!TextUtils.isEmpty(maIP) && !TextUtils.isEmpty(maPort)) { // ip port 都不为空的时候
            editText.setText(maIP + ":" + maPort);
        } else {
            editText.setText("123.103.9.184:80");
        }

        AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();


        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "连接", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String ipport = editText.getText().toString();
                if (TextUtils.isEmpty(ipport)) {

                    showToast("请输入IP地址:端口!");
                    return;
                }

                if (ipport.split(":").length != 2) {
                    showToast("IP地址:端口输入有误!");
                    return;
                }

                String ip = ipport.split(":")[0];
                String port = ipport.split(":")[1];

                writeLocationFile("ip", ip);
                writeLocationFile("port", port);

                BaseApp_lib.setIp(ip);
                BaseApp_lib.setPort(port);

            }
        });


        dialog.show();


        // 确定按钮
        Button btnpostion = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        Button btnNegative =
                dialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE);

        if (null != btnpostion) {
            btnNegative.setTextSize(15);
            btnpostion.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Button temp = (Button) v;
                    temp.setBackgroundColor(getResources().getColor(R.color.transparent));
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            temp.setTextColor(getResources().getColor(R.color.lanlan));
                            break;
                        case MotionEvent.ACTION_MOVE:
                            temp.setTextColor(getResources().getColor(R.color.lanlan));
                            break;
                        case MotionEvent.ACTION_UP:
                            temp.setTextColor(getResources().getColor(R.color.huihui));
                            break;
                    }
                    return false;
                }
            });

        }
        if (null != btnNegative) {
            btnNegative.setTextSize(15);
            // 字体颜色
            btnNegative.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Button temp = (Button) v;
                    temp.setBackgroundColor(getResources().getColor(R.color.transparent));
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            temp.setTextColor(getResources().getColor(R.color.lanlan));
                            break;
                        case MotionEvent.ACTION_MOVE:
                            temp.setTextColor(getResources().getColor(R.color.lanlan));
                            break;
                        case MotionEvent.ACTION_UP:
                            temp.setTextColor(getResources().getColor(R.color.huihui));
                            break;
                    }
                    return false;
                }
            });

        }

    }

    @Override
    public void initData() {


    }


    private String userName;
    private String userPW;


    /***
     * 调用后台服务
     */
    private void callServiceEx(boolean isAuto) {

        JSONObject json = new JSONObject();
        try {

            // 增加动态头像所需ip及端口地址参数
            json.put("serviceIP", BaseApp_lib.getIp() + ":" + BaseApp_lib.getPort());
            json.put("transtype", "pt_login");
            json.put("usercode", username.getText().toString());
            json.put("password", password.getText().toString());
            json.put(
                    "password",
                    Base64.encodeToString(password.getText().toString().trim()
                            .getBytes(Charset.forName("UTF-8")), 0));
            json.put("accountCode", "jrpt");
            if (!NetUtil.isNetConnected(this)) {
                showToast("当前网络不可用,请检查!");
                return;
            } else {
                MAServices_lib.callMACommonService(this, new ServiceCallback() {
                    @Override
                    public void execute(JSONObject json1) {
                        JSONObject json = (JSONObject) json1.opt("result");
                        Object obj = json.opt("retflag");
                        // 有错误的时候
                        if (null != obj) {
                            String retflag = json.opt("retflag") + "";
                            if (retflag.equals("1")) {
                                showToast(json.optString("msg"));
                                return;
                            }
                        }

                        String userid = json.opt("userid") + "";
                        String userid_name = json.opt("username") + "";
                        // 用户头像
                        String avatar_url = json.opt("avatar_url") + "";
                        String groud_id = json.opt("usergroup_id") + "";
                        // 构建用户信息对象
                        UserInfo_lib userInfo = new UserInfo_lib();
                        userInfo.setIcon_url(avatar_url);
                        userInfo.setGroup_id(groud_id);
                        userInfo.setUserName(userName);
                        userInfo.setPassword(userPW);
                        userInfo.setUserid(userid);
                        userInfo.setUserid_name(userid_name);
                        userInfo.setSessionkey(json.optString("sessionkey"));

                        //把用户信息写进本地
                        writeLocationObject(Constant.userInfo, userInfo);


                        //showToast("登录成功");


                        Message message = Message.obtain();

                        if (null != type) {
                            if (type.equals(Constant.approvetype)) { // 移动审批
                                message.what = 0;
                            } else if (type.equals(Constant.applicationtype)) { // 应用
                                message.what = 1;
                            } else if (type.equals(Constant.contactstype)) {  // 通讯录
                                message.what = 2;
                            } else if (type.equals(Constant.messagetype)) { // 消息
                                message.what = 3;
                            } else if (type.equals(Constant.trendstype)) { // 动态
                                message.what = 4;
                            } else if (type.equals(Constant.apptype)) { //app
                                message.what = 5;
                            } else if (type.equals(Constant.tasktype)) { //task manager
                                message.what = 6;
                            } else if (type.equals(Constant.minitype)) { //mini pro
                                message.what = 7;
                            } else{
                                message.what = -2;
                            }
                        } else {
                            message.what = -1;
                        }


                        //message.what = 6;//暂时写死，默认任务管理

                        // 添加监听了自己处理
                        if (loginlistener != null) {
                            loginlistener.onLoginListener();
                        } else { // 否则系统处理(需要传回来，要启动的页面等)
                            handler.sendMessage(message);
                        }


                    }

                    @Override
                    public void error(String arg0, String arg1) {

                        if (!TextUtils.isEmpty(arg1)) {
                            // 设置登录按钮可用性(登录请求后台有反应后可用)
                            if (arg1.equals("received a null object.")) {
                                mActivity.showMessage("可能ma地址有误,\n"+arg0 + " - " + arg1);
                            } else if (!arg1.trim().equals("")) {
                                mActivity.showMessage(arg0 + " - " + arg1);
                            }
                        }
                        LogUtils.e(arg0 + " -> " + arg1);





                    }
                }, json);
            }

        } catch (Exception e) {
            LogUtils.e(e);
            e.printStackTrace();
        }
    }


    OpenAppReceiver_lib receiver = null;
    IntentFilter filter;


    @Override
    protected void onResume() {
        super.onResume();


        // 注册广播接收
        receiver = new OpenAppReceiver_lib();
        filter = new IntentFilter();
        filter.addAction(Constant.approve_receiver);//移动审批
        filter.addAction(Constant.application_receiver);// 应用
        filter.addAction(Constant.contacts_receiver);// 通讯录
        filter.addAction(Constant.message_receiver);// 消息
        filter.addAction(Constant.trends_receiver);//动态
        filter.addAction(Constant.app_receiver);//combine
        filter.addAction(Constant.task_receiver);//任务管理
        filter.addAction(Constant.mini_receiver);// mini
        registerReceiver(receiver, filter);



        // 由用户名和密码的情况下，默认带出来
        UserInfo_lib userInfo = readLocationObject(Constant.userInfo, UserInfo_lib.class);
        if (null != userInfo){
            username.setText(userInfo.getUserName());
            password.setText(userInfo.getPassword());
        }


        // 自动登录按钮
        String autoflag = readLocationValue("autologin");



        if (autoflag.equals("true")){ //执行自动登录
            switchs.setState(true);


            userName = username.getText().toString();
            userPW = password.getText().toString();


            if (TextUtils.isEmpty(userName)) {
                showToast("用户名不可为空");
                return;
            }

            if (TextUtils.isEmpty(userPW)) {
                showToast("密码不可为空");
                return;
            }


            // 判断网络
            if (!NetUtil.isNetConnected(LoginBaseActivity_lib.this)) {
                showToast("当前网络不可用,请检查!");
                return;
            }


            callServiceEx(true);

        }else {
            switchs.setState(false);
        }




    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Intent broadcast;
            Bundle bundle;
            bundle = new Bundle();
            bundle.putString(Constant.packagename, packagename);
            bundle.putString(Constant.openactivity, openactivity);


            switch (msg.what) {
                case 0:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.approve_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;

                case 1:

                    LogUtils.e("1   ---    application_receiver ");
                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.application_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;
                case 2:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.contacts_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;
                case 3:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.message_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;
                case 4:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.trends_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;

                case 5:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.app_receiver);
                    // 门户的
                    bundle.putString(Constant.packagename, "com.yonyou.jrmob");
                    bundle.putString(Constant.openactivity, "com.yonyou.jrmob.baseui.activity.MainPageActivity_ap");

                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;

                case 6:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.task_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;
                case 7:

                    //使用静态的方式注册广播，可以使用显示意图进行发送广播
                    broadcast = new Intent(Constant.mini_receiver);
                    broadcast.putExtras(bundle);
                    sendBroadcast(broadcast, null);

                    break;

                case -1:

                    showToast("type为未知类型1");

                case -2:


                    break;
                default:

                    break;
            }

        }
    };

    @Override
    protected void onPause() {
        super.onPause();

        if (null != receiver) {
            unregisterReceiver(receiver);
        }

    }


}
